import 'package:flutter/cupertino.dart';
import 'package:kq_flutter_core_widget/utils/kq_screen_util.dart';
import 'package:intl/intl.dart';
import 'package:json_annotation/json_annotation.dart';
import 'package:kq_flutter_core_widget/utils/ex/kq_ex.dart';
import 'package:kq_flutter_core_widget/utils/text_input_format_utils.dart';
import 'package:kq_flutter_core_widget/widgets/image/kq_image.dart';
import 'package:kq_flutter_widgets/widgets/divider/kq_divider.dart';
import 'package:kq_flutter_widgets/widgets/tip/kq_tip.dart';

import '../../config/kq_global.dart';
import '../../resources/images.dart';
import '../../resources/kq_theme_colors.dart';
import '../../widgets/seekbar/seek_bar.dart';
import '../../widgets/textFiled/kq_textfiled.dart';

/// @author 高裕
/// 科学试模输入模块
class SimpleScienceTestMoldEdit<T extends SimpleScienceTestMoldEditEntity>
    extends StatefulWidget {
  const SimpleScienceTestMoldEdit({
    super.key,
    required this.entity,
  });

  final T entity;

  @override
  State<StatefulWidget> createState() => SimpleScienceTestMoldEditState();
}

class SimpleScienceTestMoldEditState extends State<SimpleScienceTestMoldEdit> {
  final numberFormat = NumberFormat("#.##");

  // 用于判断改变幅度是否超过0.01，减少回调频率
  double? oldValue;

  @override
  void initState() {
    super.initState();
    widget.entity.state = this;
    widget.entity.value ??= widget.entity.min;
    oldValue = widget.entity.value;
  }

  @override
  void didUpdateWidget(covariant SimpleScienceTestMoldEdit oldWidget) {
    super.didUpdateWidget(oldWidget);
    widget.entity.state = this;
    widget.entity.value ??= widget.entity.min;
    oldValue = widget.entity.value;
  }

  /// 主动刷新方法
  update() {
    if (mounted) {
      setState(() {});
    }
  }

  /// 主动清空方法
  clear() {
    if (mounted) {
      widget.entity.value = widget.entity.min;
      oldValue = widget.entity.value;
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    if (widget.entity.min == null ||
        widget.entity.max == null ||
        widget.entity.paramTitle.isNullOrEmpty) {
      return Container();
    }
    return Container(
      color: KqThemeColors.bgWhite,
      child: Column(
        children: [
          SizedBox(
            height: 12.r,
          ),
          Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              SizedBox(
                width: 16.r,
              ),
              if (widget.entity.pointColor != null)
                _createPoint(widget.entity.pointColor!),
              if (widget.entity.paramPic.isNotNullOrEmpty)
                Container(
                  margin: EdgeInsets.only(right: 8.r),
                  child: KqImage.assets(
                    url: widget.entity.paramPic!,
                    width: 16.r,
                    height: 16.r,
                  ),
                ),
              Container(
                margin: EdgeInsets.only(right: 8.r),
                child: Text(
                  widget.entity.paramTitle!,
                  style: TextStyle(
                    color: KqThemeColors.text26,
                    fontSize: 12.sp,
                  ),
                ),
              ),
              if (widget.entity.paramTips.isNotNullOrEmpty)
                Container(
                  margin: EdgeInsets.only(right: 8.r),
                  child: KqTip(
                    widget.entity.paramTips!,
                    tipsTextAlign: TextAlign.start,
                    child: KqImage.assets(
                      url: Images.commonIcBangzhu,
                      package: KqGlobal.packageName,
                      width: 16.r,
                      height: 16.r,
                    ),
                  ),
                ),
              if (widget.entity.customRightView != null &&
                  widget.entity.value != null)
                widget.entity.customRightView!
                    .call(widget.entity.value, widget.entity),
              SizedBox(
                width: 8.r,
              ),
            ],
          ),
          Container(
            width: double.infinity,
            height: 40.r,
            padding: EdgeInsets.symmetric(horizontal: 16.r),
            margin: EdgeInsets.only(top: 3.r, bottom: 5.r),
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                Container(
                  width: 48.r,
                  alignment: Alignment.centerRight,
                  child: Text(
                    numberFormat.format(widget.entity.min),
                    style: TextStyle(
                      color: KqThemeColors.text59,
                      fontSize: 12.sp,
                    ),
                  ),
                ),
                Expanded(
                    child: SeekBar(
                  bgColor: KqThemeColors.bgF0,
                  oneSeekColor: KqThemeColors.textLightBlue,
                  max: widget.entity.max! - widget.entity.min!,
                  valueOneSeekBar: changeValueToSeekBarValue(),
                  progressHeight: 6.r,
                  height: 40.r,
                  oneSeekWidget: KqImage.assets(
                    url: Images.commonIcHuakuai28,
                    package: KqGlobal.packageName,
                    width: 40.r,
                    height: 40.r,
                  ),
                  callback: (double one, double two) {
                    changeSeekBarValueToValue(one);
                    if ((widget.entity.value! - oldValue!).abs() >= 0.01) {
                      oldValue = widget.entity.value;
                      widget.entity.onMove?.call(
                          double.tryParse(
                              widget.entity.value!.toStringAsFixed(2)),
                          widget.entity);
                    }
                    setState(() {});
                  },
                  callbackWhenFinish: (double one, double two) {
                    widget.entity.onMoveEnd?.call(
                        double.tryParse(
                            widget.entity.value!.toStringAsFixed(2)),
                        widget.entity);
                  },
                )),
                Container(
                  width: 48.r,
                  alignment: Alignment.centerLeft,
                  child: Text(
                    numberFormat.format(widget.entity.max),
                    style: TextStyle(
                      color: KqThemeColors.text59,
                      fontSize: 12.sp,
                    ),
                  ),
                ),
                SizedBox(width: 4.r),
                Container(
                  width: 56.r,
                  height: 28.r,
                  color: KqThemeColors.bgF5,
                  alignment: Alignment.center,
                  child: KqTextFiled(
                    multiline: false,
                    maxLines: 1,
                    inputType: TextInputType.number,
                    inputFormatters:
                        TextInputFormatUtils.decimal(decimalLength: 2),
                    textColor: valueIsInLimit()
                        ? KqThemeColors.text26
                        : KqThemeColors.textRed,
                    fontSize: 14.sp,
                    textAlign: TextAlign.center,
                    newValue: widget.entity.value == null
                        ? null
                        : numberFormat.format(widget.entity.value),
                    onChanged: (text) {
                      double? nowValue = double.tryParse(text);
                      if (widget.entity.value != nowValue) {
                        widget.entity.value = nowValue;
                        if (valueIsInLimit()) {
                          oldValue = widget.entity.value;
                          widget.entity.onTextChange?.call(
                              double.tryParse(
                                  widget.entity.value!.toStringAsFixed(2)),
                              widget.entity);
                        }
                        setState(() {});
                      }
                    },
                  ),
                )
              ],
            ),
          ),
          KqDivider(
            height: 1.r,
          ),
        ],
      ),
    );
  }

  double changeValueToSeekBarValue() {
    if (widget.entity.value == null ||
        widget.entity.value! < widget.entity.min!) {
      return 0;
    } else if (widget.entity.value! > widget.entity.max!) {
      return widget.entity.max! - widget.entity.min!;
    } else {
      return widget.entity.value! - widget.entity.min!;
    }
  }

  void changeSeekBarValueToValue(double seekBarValue) {
    widget.entity.value = seekBarValue + widget.entity.min!;
  }

  /// 值是否处于上下限内
  bool valueIsInLimit() {
    if (widget.entity.value != null &&
        widget.entity.value! <= widget.entity.max! &&
        widget.entity.value! >= widget.entity.min!) {
      return true;
    }
    return false;
  }

  /// 生成红/绿点
  Widget _createPoint(Color color) {
    return Container(
      width: 8.r,
      height: 8.r,
      margin: EdgeInsets.only(right: 8.r),
      decoration: BoxDecoration(
        color: color,
        borderRadius: BorderRadius.all(Radius.circular(4.r)),
      ),
    );
  }
}

/// 科学试模输入模块 抽象类
abstract class SimpleScienceTestMoldEditEntity {
  /// 当前值
  double? get value;

  set value(double? value);

  /// 最大值
  double? get max;

  /// 最小值
  double? get min;

  /// 点的颜色
  Color? get pointColor;

  /// 参数图片
  String? get paramPic;

  /// 参数标题
  String? get paramTitle;

  /// 参数提示
  String? get paramTips;

  /// 一般用于刷新和清空
  @JsonKey(includeFromJson: false, includeToJson: false)
  SimpleScienceTestMoldEditState? state;

  /// 用于子类传参
  SimpleScienceTestMoldEditEntity(
      {this.customRightView, this.onMove, this.onMoveEnd, this.onTextChange});

  /// 右侧自定义view
  @JsonKey(includeFromJson: false, includeToJson: false)
  Widget Function(double? value, SimpleScienceTestMoldEditEntity entity)?
      customRightView;

  /// 滑动的回调
  @JsonKey(includeFromJson: false, includeToJson: false)
  Function(double? value, SimpleScienceTestMoldEditEntity entity)? onMove;

  /// 滑动结束的回调
  @JsonKey(includeFromJson: false, includeToJson: false)
  Function(double? value, SimpleScienceTestMoldEditEntity entity)? onMoveEnd;

  /// 文本变化的回调
  @JsonKey(includeFromJson: false, includeToJson: false)
  Function(double? value, SimpleScienceTestMoldEditEntity entity)? onTextChange;
}

/// 科学试模输入模块(在没实体可以继承时使用的预设)
class NormalSimpleScienceTestMoldEditEntity
    extends SimpleScienceTestMoldEditEntity {
  NormalSimpleScienceTestMoldEditEntity({
    required this.max,
    required this.min,
    required this.paramTitle,
    this.pointColor,
    this.paramPic,
    this.paramTips,
    this.value,
    super.onMove,
    super.onMoveEnd,
    super.onTextChange,
    super.customRightView,
  });

  @override
  double? max;

  @override
  double? min;

  @override
  String? paramPic;

  @override
  String? paramTips;

  @override
  String? paramTitle;

  @override
  Color? pointColor;

  @override
  double? value;
}
